package com.orangelife.mobile.hourlyEmployee.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.common.sp.CommSp2;
import com.common.sp.ShoppingSp;
import com.curry.android.http.HttpUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.JSONHelper;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.hourlyEmployee.entity.ServiceInformationBean;
import com.orangelife.mobile.util.DateUtil;
import com.orangelife.mobile.util.EmojiFilter;
import com.orangelife.mobile.util.StringUtil;
import com.orangelife.mobile.util.ToastHelper;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PlaceOrderActivity extends OrangeLifeBaseActivity {

    /**
     * 服务价格
     */
    private TextView tvServicePrice;
    /**
     * 备注
     */
    private EditText etRemarks;
    /**
     * 服务
     */
    private LinearLayout llServiceTime;
    /**
     * 下单按钮
     */
    private Button btnPlaceOrder;
    /**
     * 标题中间
     */
    private TextView tvTitle;
    /**
     * 标题右边
     */
    private TextView tvTitleRight;
    /**
     * 地址名字
     */
    private TextView tvName;
    /**
     * 服务时间字
     */
    private TextView tvServiceTime;
    /**
     * 服务时间
     */
    private TextView tvServiceTimeContent;
    /**
     * 电话
     */
    @SuppressWarnings("unused")
    private TextView tvPhoneNumber;
    /**
     * 地址
     */
    @SuppressWarnings("unused")
    private TextView tvAddress;
    /**
     * 地址提示
     */
    private TextView tvTip;
    /**
     * 时间提示
     */
    private TextView tvTipTime;

    private ImageView ivJiantou;
    /**
     * 接收从后台传来的数据
     */
    private Map<String, Object> mapDetail;
    private Dialog dialog;
    /**
     * 限制的最大字数
     */
    int num = 50;
    String str = "";
    /**
     * 服务时间的时间戳
     */
    private String serviceDate = "";
    /**
     * 服务时间的小时
     */
    private double hour = 0;

    public static List<Map<String, Object>> mapTime = new ArrayList<Map<String, Object>>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hourly_employee_place_order);
        initeView();
        findView();
    }

    private void initeView() {
        tvServicePrice = (TextView) findViewById(R.id.tvServicePrice);
        etRemarks = (EditText) findViewById(R.id.etRemarks);
        llServiceTime = (LinearLayout) findViewById(R.id.llServiceTime);
        btnPlaceOrder = (Button) findViewById(R.id.btnPlaceOrder);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitleRight = (TextView) findViewById(R.id.tv_title_right);
        tvName = (TextView) findViewById(R.id.tv_username);
        tvServiceTime = (TextView) findViewById(R.id.tvServiceTime);
        tvServiceTimeContent = (TextView) findViewById(R.id.tvServiceTimeContent);
        tvPhoneNumber = (TextView) findViewById(R.id.tv_userphone);
        tvAddress = (TextView) findViewById(R.id.tv_address);
        tvTip = (TextView) findViewById(R.id.tvTip);
        tvTipTime = (TextView) findViewById(R.id.tvTipTime);
        ivJiantou = (ImageView) findViewById(R.id.ivJiantou);
    }

    private void findView() {
        tvTitle.setText(R.string.hourly_employee);
        tvTip.setText(R.string.no_address);
        tvTitleRight.setText(R.string.service_introduction);
        llServiceTime.setOnClickListener(listener);
        btnPlaceOrder.setOnClickListener(listener);
        tvTitleRight.setOnClickListener(listener);
        dialog = DialogHelper.getInstance().createLoadingDialog(
                PlaceOrderActivity.this, Constant.LOADING);
        dialog.show();
        getServiceInformation();
        etRemarks.addTextChangedListener(new TextWatcher() {
            private CharSequence temp;
            private int selectionStart;
            private int selectionEnd;
            /** 输入表情前的光标位置 */
            @SuppressWarnings("unused")
            private int cursorPos;
            /** 输入表情前EditText中的文本 */
            private String tmp;
            /** 是否重置了EditText的内容 */
            private boolean resetText;

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if ("".equals(str)) {
                    if (!resetText) {
                        /** 表情符号的字符长度最小为2 */
                        if (count >= 2) {
                            /** 提取输入的长度大于2的文本 */
                            if (s.length() <= num) {
                                CharSequence input = s.subSequence(start, start
                                        + count);
                                if (!EmojiFilter.containsEmoji(input.toString())) {
                                    resetText = true;
                                    /** 是表情符号就将文本还原为输入表情符号之前的内容 */
                                    etRemarks.setText(tmp);
                                    etRemarks.invalidate();
                                    ToastHelper.getInstance()._toast("不支持表情输入");
                                    etRemarks.setSelection(tmp.length());
                                }
                            } else {
                                str = "over";
                            }
                        }
                    } else {
                        resetText = false;
                    }
                }

                temp = s;
                Log.e("hhhhhhhh", s + "");
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                if (!resetText) {
                    cursorPos = etRemarks.getSelectionEnd();
                    /**
                     * 这里用s.toString()而不直接用s是因为如果用s，那么，tmp和s在内存中指向的是同一个地址，s改变了，
                     * tmp也就改变了，那么表情过滤就失败了
                     */
                    tmp = s.toString();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                selectionStart = etRemarks.getSelectionStart();
                selectionEnd = etRemarks.getSelectionEnd();
                if (temp.length() > num) {
                    s.delete(selectionStart - 1, selectionEnd);
                    int tempSelection = selectionStart;
                    ToastHelper.getInstance()._toast("备注要在50字以内");
                    etRemarks.setText(s);
                    etRemarks.setSelection(tempSelection);
                }
            }
        });
    }

    /**
     * 设置详情
     */
    private void setDetail() {

        if (mapDetail == null || mapDetail.size() == 0) {
            tvServicePrice.setText("无");
            tvServiceTimeContent.setText("所在区域尚未开通");
            tvServiceTimeContent.setTextColor(getResources().getColor(R.color.text_color_orange));
            llServiceTime.setEnabled(false);
            ivJiantou.setVisibility(View.GONE);
            btnPlaceOrder.setEnabled(false);
        } else {
            tvServicePrice.setText(mapDetail.get("priceInfo").toString());
            tvTipTime.setText(mapDetail.get("tip").toString());
            llServiceTime.setEnabled(true);
            tvServiceTimeContent.setTextColor(getResources().getColor(R.color.DarkGray));
            ivJiantou.setVisibility(View.VISIBLE);
            tvServiceTimeContent.setText("");
            btnPlaceOrder.setEnabled(true);
        }
    }

    /**
     * 监听器
     */
    private OnClickListener listener = new OnClickListener() {

        @SuppressWarnings("unchecked")
        @Override
        public void onClick(View view) {
            Intent intent = new Intent();
            switch (view.getId()) {
                case R.id.llServiceTime:
                    @SuppressWarnings("unused")
                    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                    String tip = mapDetail.get("tip").toString();
                    mapTime = (List<Map<String, Object>>) mapDetail.get("ts");
                    if (mapTime == null || mapTime.size() == 0) {
                        ToastHelper.getInstance().displayToastWithQuickClose("暂无服务时间");
                        return;
                    }
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("tip", (Serializable) tip);
                    intent.putExtras(bundle);
                    intent.setClass(PlaceOrderActivity.this,
                            ServiceTimeActivity.class);
                    startActivityForResult(intent, 16);
                    break;
                case R.id.btnPlaceOrder:
                    if (!"".equals(tvName.getText().toString())) {
                        if (!StringUtil.isBlank(tvServiceTimeContent.getText()
                                .toString())) {
                            // 下单
                            placeOrder();
                        } else {
                            ToastHelper.getInstance().displayToastWithQuickClose(
                                    getResources().getString(
                                            R.string.please_select_service_time));
                        }
                    } else {
                        ToastHelper.getInstance().displayToastWithQuickClose(
                                getResources().getString(
                                        R.string.please_fill_address));
                    }
                    break;
                case R.id.tv_title_right:
                    if (mapDetail == null || mapDetail.size() == 0) {
                        ToastHelper.getInstance()._toast("暂无该地区服务介绍");
                        return;
                    }
                    intent.putExtra("activ", 1);
                    intent.putExtra("url", mapDetail.get("url").toString());
                    //                    intent.putExtra("url","http://www.baidu.com");
                    intent.setClass(PlaceOrderActivity.this, ServiceIntroductionActivity.class);
                    startActivity(intent);
                    break;

                default:
                    break;
            }
        }
    };

    /**
     * 获取服务信息
     */
    private void getServiceInformation() {
        Map<String, Object> map = new HashMap<>();
        String districtID = ShoppingSp.getTradeDistrictID();
        if (TextUtils.isEmpty(districtID)) {
            districtID = CommSp2.getDistrictID();
        }
        map.put("districtID", districtID);
        JSONRequest.getInstance().sendRequest(JSONRequest.GET,
                Constant.URL_GET_SERVICE_INFROMATION, map, handler, 2,
                HttpUtil.ACTION_URI);
    }

    /**
     * 下单
     */
    private void placeOrder() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("serviceDate", serviceDate);
        map.put("hours", hour);
        map.put("serviceID", mapDetail.get("serviceID").toString());
        map.put("addressID", ShoppingSp.getTradeAddressID());
        if (!StringUtil.isBlank(etRemarks.getText().toString())) {
            map.put("remark", etRemarks.getText().toString());
        }
        JSONRequest.getInstance().sendRequest(JSONRequest.POST,
                Constant.URL_HOURLY_EMPLOYEE_PLACE_ORDER, map, handler, 1,
                HttpUtil.ACTION_JSON);
    }

    /**
     * 接收处理线程返回的消息
     */
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @SuppressWarnings("unchecked")
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case Constant.WHAT_ERROR_HTTP:
                    ToastHelper.getInstance()._toast(String.valueOf(msg.obj));
                    break;
                case 2:
                    mapDetail = new HashMap<String, Object>();

                    mapDetail = (Map<String, Object>) JSONHelper.jsonToMap(
                            msg.obj.toString()).get("entity");
                    DialogHelper.closeDialog(dialog);
                    setDetail();
                    break;
                case 1:
                    String errInfo = JSONHelper.jsonToMap(msg.obj.toString())
                            .get("errInfo").toString();
                    if (errInfo.equals("OK")) {
                        DialogHelper.closeDialog(dialog);
                        Map<String, Object> map = new HashMap<String, Object>();
                        map = (Map<String, Object>) JSONHelper.jsonToMap(
                                msg.obj.toString()).get("entity");
                        ServiceInformationBean.setServiceOrderID(map.get("serviceOrderID").toString());
                        IntentHelper.getInstances().getIntent(PlaceOrderActivity.this,
                                OrderSuccessActivity.class);
                        finish();
                    } else {
                        DialogHelper.closeDialog(dialog);
                        ToastHelper.getInstance()._toast(
                                getResources().getString(
                                        R.string.complaintes_sumbite_fail));
                    }
                    break;
            }
            if (dialog != null) {
                dialog.dismiss();
            }
        }

        ;
    };

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case 16:
                if (data != null) {
                    serviceDate = data.getStringExtra("time");
                    String hourStr = data.getStringExtra("hourNum");
                    hour = Double.parseDouble(hourStr.substring(0, hourStr.length() - 2));
                    tvServiceTime.setText(getResources().getString(R.string.service_time));
                    tvServiceTimeContent.setText(DateUtil.getInstance().tranStringForDate_33(data.getStringExtra("time"))
                            + " " + data.getStringExtra("hourNum"));
                }
                break;
            case Activity.RESULT_FIRST_USER:
                getServiceInformation();
                break;
            default:
                break;
        }
    }

}
